﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Kooboo.Web.Mvc;
using System.Web.Compilation;
using System.Reflection;
using System.Threading;
using System.Globalization;
using Kooboo.Commerce;

using System.IO;
using Kooboo.Connect;
using Kooboo.IoC;

using System.Web.Script.Serialization;
using Kooboo.Commerce.Contexts.ShopSettings;


namespace Kooboo.Web
{

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterRoutes(RouteCollection routes)
        {

            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            //account
            RegisterRoute(routes, "web_account_profile", "my", new { controller = "Account", action = "index" });
            RegisterRoute(routes, "web_account_passowrd", "my/password", new { controller = "Account", action = "Password" });
            RegisterRoute(routes, "web_account_address", "my/address", new { controller = "Account", action = "Address" });
            RegisterRoute(routes, "web_account_address_edit", "my/address/edit/{id}", new { controller = "Account", action = "AddressEdit", id = UrlParameter.Optional });
            RegisterRoute(routes, "web_account_address_delete", "my/address/delete/{id}", new { controller = "Account", action = "Delete", id = UrlParameter.Optional });
            RegisterRoute(routes, "web_account_order", "my/order/{page}", new { controller = "Account", action = "Orderlist", page = UrlParameter.Optional });
            RegisterRoute(routes, "web_account_order_pay", "my/order/pay/{orderid}", new { controller = "Account", action = "Pay" });
            RegisterRoute(routes, "web_account_order_thankyou", "my/thankyou", new { controller = "Account", action = "Thankyou" });
            RegisterRoute(routes, "web_account_order_error", "my/error", new { controller = "Account", action = "Error" });
            RegisterRoute(routes, "web_account_orderdetail", "my/order/detail/{orderid}", new { controller = "Account", action = "Order" });

            //Support ticket
            RegisterRoute(routes, "web_account_supportticket", "my/supportticket/{page}", new { controller = "Account", action = "SupportTicket", page = UrlParameter.Optional });
            RegisterRoute(routes, "web_account_supportticket_detail", "my/supportticket/detail/{id}", new { controller = "Account", action = "SupportTicketDetail", id = UrlParameter.Optional });

            //cart
            RegisterRoute(routes, "web_cart_index", "cart", new { controller = "Cart", action = "Index" });
            RegisterRoute(routes, "web_cart_add", "cart/add", new { controller = "Cart", action = "Add" });
            RegisterRoute(routes, "web_cart_remove", "cart/{id}-remove-{quantity}", new { controller = "Cart", action = "Remove" });
            RegisterRoute(routes, "web_cart_checkout", "cart/checkout", new { controller = "Cart", action = "Checkout" });
            RegisterRoute(routes, "web_cart_payment", "cart/payment", new { controller = "Cart", action = "Payment" });
            RegisterRoute(routes, "web_cart_pay", "cart/pay", new { controller = "Cart", action = "Pay" });

            //content
            RegisterRoute(routes, "web_content_links_help", "faq", new { controller = "Content", action = "Help" });
            RegisterRoute(routes, "web_content_links_about", "about", new { controller = "Content", action = "About" });
            RegisterRoute(routes, "web_content_links_contact", "contact", new { controller = "Content", action = "Contact" });
            RegisterRoute(routes, "web_content_links_terms", "terms", new { controller = "Content", action = "Terms" });
            RegisterRoute(routes, "web_content_links_privacy", "privacy", new { controller = "Content", action = "Privacy" });

            //review
            RegisterRoute(routes, "web_product_view_review", "products/review/{productId}/{page}", new { controller = "Product", action = "Review", page = UrlParameter.Optional });
            //question
            RegisterRoute(routes, "web_product_view_question", "products/question/{productId}/{page}", new { controller = "Product", action = "Question", page = UrlParameter.Optional });
            //product
            RegisterRoute(routes, "web_product_view", "products/{id}/{orderid}", new { controller = "Product", action = "View", orderid = UrlParameter.Optional });

            //category
            RegisterRoute(routes, "web_category_index", "categories/{id}", new { controller = "Category", action = "Index" });

            //brand
            RegisterRoute(routes, "web_brand_index", "brands/{id}", new { controller = "Brand", action = "Index" });

            //register
            RegisterRoute(routes, "web_register", "register", new { controller = "Register", action = "Index" });
            //register_complete
            RegisterRoute(routes, "web_register_complete", "register/complete", new { controller = "Register", action = "Complete" });

            //status
            RegisterRoute(routes, "web_status_logon", "logon", new { controller = "Status", action = "LogOn" });
            RegisterRoute(routes, "web_status_logoff", "logoff", new { controller = "Status", action = "LogOff" });

            //default
            RegisterRoute(routes, "web_default", "{controller}", new { controller = "Home", action = "Index" });



            //#region category
            //routes.MapRoute("category.index",
            //    "category/{id}",
            //    new { controller = "Category",action="index"});
            //#endregion

            //var route = routes.MapRoute(
            //    "Default", // Route name
            //    "{controller}/{action}/{id}", // URL with parameters
            //    new { controller = "Home", action = "Index", id = UrlParameter.Optional }, // Parameter defaults
            //    new string[] { "Kooboo.Web.Controllers" }
            //);


            //route.DataTokens["UseNamespaceFallback"] = false;
            //Kooboo.Web.Mvc.Routing.RouteTableRegister.RegisterRoutes(routes);

            ModelMetadataProviders.Current = new KoobooDataAnnotationsModelMetadataProvider();

            ModelValidatorProviders.Providers.RemoveAt(0);
            ModelValidatorProviders.Providers.Insert(0, new KoobooDataAnnotationsModelValidatorProvider());



        }

        static void RegisterRoute(RouteCollection routes, string name, string url, object defaults)
        {
            routes.MapRoute(name, url, defaults, new string[] { "Kooboo.Web.Controllers" });
        }

        protected void Application_Start()
        {
            //AreaRegistration.RegisterAllAreas();

            foreach (var area in ObjectContainer.CreateInstances<AreaRegistration>())
            {
                AreaRegistrationContext context = new AreaRegistrationContext(area.AreaName, RouteTable.Routes, null);
                string str = area.GetType().Namespace;
                if (str != null)
                {
                    context.Namespaces.Add(str + ".*");
                }
                area.RegisterArea(context);

            }

            RegisterRoutes(RouteTable.Routes);
            RegisterAllModelBinders();

        }

        private static void RegisterAllModelBinders()
        {
            //  ModelBinders.Binders.Add(typeof(ICart), new CartBinder());
            //  ModelBinders.Binders.Add(typeof(ICartItem), new CartItemBinder());
        }

        protected void Application_BeginRequest(object o, EventArgs e)
        {

            var file = HttpContext.Current.Request.PhysicalPath;

            var fi = new FileInfo(file);

            if (string.IsNullOrWhiteSpace(fi.Extension))
            {
                var host = new ServiceHost();

                var shopSetting = host.GetShopSettings();

                Thread.CurrentThread.CurrentCulture = new CultureInfo(shopSetting.ThreadCulture);
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(shopSetting.ThreadCulture);
            }
        }

        protected void Application_EndRequest(object o, EventArgs e)
        {
            ContextContainer.Current.Dispose();


            var request = HttpContext.Current.Request;

            if (request != null)
            {
                if (request.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    var response = HttpContext.Current.Response;

                    if (response.StatusCode == 301 || response.StatusCode == 302)//redirect to url
                    {
                        response.StatusCode = 278;
                        response.ClearContent();
                    }
                }
            }
        }

        void Application_Error(object sender, EventArgs e)
        {
            var request = HttpContext.Current.Request;

            if (request != null)
            {
                //    if ((request["X-Requested-With"] == "XMLHttpRequest")  || ((request.Headers != null) && (request.Headers["X-Requested-With"].Contains("XMLHttpRequest"))))
                if (request.RequestContext.HttpContext.Request.IsAjaxRequest())
                {
                    var response = HttpContext.Current.Response;
                    Exception ex = Server.GetLastError().GetBaseException();

                    response = HttpContext.Current.Response;
                    response.ClearContent();
                    response.ContentType = "text/html";

                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    response.Write(serializer.Serialize(new { Error = ex.Message, ex.Source, ex.StackTrace }));

                    Server.ClearError();
                }
            }
        }

    }
}